<template>
  <div>
    <nav-header></nav-header>
    <nav-bread>
      <span>Goods</span>
    </nav-bread>
    <div class="accessory-result-page accessory-page">
      <div class="container">
        <div class="filter-nav">
          <span class="sortby">Sort by:</span>
          <a href="javascript:void(0)" class="default cur">Default</a>
          <a href="javascript:void(0)"
            class="price"
            @click="togglePriceSort">
            Price
            <span v-if="queryObj.sort === 1">↑</span>
            <span v-else>↓</span>
            <!-- <svg class="icon icon-arrow-short"><use xlink:href="#icon-arrow-short"></use></svg> -->
          </a>
          <a href="javascript:void(0)"
            class="filterby stopPop"
            @click="showPriceFilter">
            Filter by
          </a>
        </div>
        <div class="accessory-result">
          <!-- filter -->
          <div class="filter stopPop"
            :class="{'filterby-show': showFilterFlag}"
            id="filter">
            <dl class="filter-price">
              <dt>Price:</dt>
              <dd>
                <a href="javascript:void(0)"
                  :class="{'cur': 'all' === queryObj.priceLevel}"
                  @click="setPriceFilter('all')">
                  All
                </a>
              </dd>
              <dd v-for="(filter, index) in priceFilter"
              :key="index">
                <a href="javascript:void(0)"
                  :class="{'cur': index === queryObj.priceLevel}"
                  @click="setPriceFilter(index)">
                  {{ filter.floor }} - {{ filter.ceiling }}
                </a>
              </dd>
            </dl>
          </div>

          <!-- search result accessories list -->
          <div class="accessory-list-wrap">
            <div class="accessory-list col-4">
              <ul class="clearfix">
                <li v-for="item in goodsList"
                  :key="item.productId">
                  <div class="pic">
                    <a href="#"><img v-lazy="`static/${item.productImage}`" :alt="item.productName"></a>
                  </div>
                  <div class="main">
                    <div class="name">{{ item.productName }}</div>
                    <div class="price">{{ item.salePrice | currency }}</div>
                    <div class="btn-area">
                      <a href="javascript:;" class="btn btn--m" @click="addToCart(item.productId)">加入购物车</a>
                    </div>
                  </div>
                </li>
              </ul>
              <div v-infinite-scroll="loadMore"
                infinite-scroll-disabled="busy"
                infinite-scroll-distance="20"
                infinite-scroll-immediate-check="false"
                class="load-more">
                <img src="./../assets/loading-spinning-bubbles.svg" v-show="loading">
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <nav-footer></nav-footer>
    <div :class="{'md-overlay': overlayFlag}" @click="closePop"></div>
    <!-- 提示登录的模态框 -->
    <modal :showModal="showModalCheckLogin" @close="showModalCheckLogin = false">
      <p slot="message">请先登录</p>
      <div slot="btnGroup">
        <button class="btn btn--m" @click="showModalCheckLogin = false">关闭</button>
      </div>
    </modal>
    <!-- 提示加入购物车成功并引导至购物车组件的模态框 -->
    <modal :showModal="showModalCart" @close="showModalCart = false">
      <p slot="message">
        <svg class="icon icon-ok icon-status-ok">
          <use xlink:href="#icon-ok"></use>
        </svg>
        加入购物车成功
      </p>
      <div slot="btnGroup">
        <a class="btn btn--m" @click="showModalCart = false">继续购物</a>
        <router-link class="btn btn--m" to="/cart">查看购物车</router-link>
      </div>
    </modal>
  </div>
</template>
<script>
import '@/assets/css/base.css'
import '@/assets/css/product.css'
import NavHeader from '@/components/NavHeader'
import NavFooter from '@/components/NavFooter'
import NavBread from '@/components/NavBread'
import Modal from '@/components/Modal'
import axios from 'axios'
import store from '../store/store'
export default {
  components: {
    NavHeader,
    NavFooter,
    NavBread,
    Modal
  },
  data () {
    return {
      goodsList: [],
      priceFilter: [
        {
          floor: '0',
          ceiling: '100'
        },
        {
          floor: '100',
          ceiling: '500'
        },
        {
          floor: '500',
          ceiling: '1000'
        },
        {
          floor: '1000',
          ceiling: '2000'
        },
        {
          floor: '2000',
          ceiling: '5000'
        }
      ],
      showModalCheckLogin: false, // 模态框：提醒用户先登录
      showModalCart: false, // 模态框：购物车操作引导（继续购物或跳转到购物车）
      overlayFlag: false, // 价格表过滤器模态框遮罩，仅用于移动端
      showFilterFlag: false, // 显示价格表过滤器模态框，仅用于移动端
      loading: false,
      queryObj: {
        // 数据库分页，请求的当前页
        page: 1,
        // 数据库分页，每页请求的商品数量
        pageSize: 8,
        // 数据库提供的接口： 1表示升序，-1表示降序
        sort: 1,
        // 根据价格区间对商品过滤
        priceLevel: 'all'
      },
      busy: false, // vue-infinite-scroll 插件控制滚动加载的变量，https://www.npmjs.com/package/vue-infinite-scroll
      appendFlag: true // 是否将新获取的商品数据追加到 goodsList 末尾
    }
  },
  methods: {
    getGoodsData () {
      const params = this.queryObj
      this.loading = true
      axios.get('/goods/list', { params })
        .then(this.getGoodsDataSucc)
    },
    getGoodsDataSucc (res) {
      res = res.data
      if (res.status === '0') {
        this.loading = false
        // 判断是否将分页获取的商品数据追加到 goodsList
        this.goodsList = this.appendFlag ? this.goodsList.concat(res.result.list) : res.result.list
        // 当分页获取的商品数据数量小于每一页商品数量 ，意味着后面没有数据了，停止获取数据
        this.busy = res.result.list.length < this.queryObj.pageSize
      }
    },
    setPriceFilter (index) {
      this.queryObj.priceLevel = index
      this.closePop()
      // 重新获取商品数据
      this.queryObj.page = 1
      this.appendFlag = false
      this.getGoodsData()
    },
    showPriceFilter () {
      this.overlayFlag = true
      this.showFilterFlag = true
    },
    closePop () {
      this.overlayFlag = false
      this.showFilterFlag = false
    },
    // 切换商品列表按照升序/降序
    togglePriceSort () {
      this.queryObj.sort *= -1
      this.queryObj.page = 1
      this.appendFlag = false
      this.getGoodsData()
    },
    loadMore () {
      this.busy = true
      this.appendFlag = true
      setTimeout(() => {
        // loading more data
        this.queryObj.page++
        this.getGoodsData()
      }, 500)
    },
    addToCart (productId) {
      // 操作数据库
      axios.post('/goods/addToCart', {
        productId
      })
        .then(res => {
          const data = res.data
          if (data.status === '0') {
            // alert(`Id 为 ${productId} 的商品已被成功添加到购物车`)
            this.showModalCart = true
            store.setCartItemQuantityAction(1)
          } else {
            this.showModalCheckLogin = true
          }
        })
    }
  },
  mounted () {
    this.getGoodsData()
  }
}
</script>

<style scoped>
  .load-more {
    text-align: center;
    padding: 20px;
  }
</style>
